package org.yzh.scheduler.component.auth;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.yzh.scheduler.component.annotations.RequiresRoles;
import org.yzh.scheduler.model.entity.UserDO;
import org.yzh.scheduler.model.enums.Role;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AuthorizationInterceptor extends HandlerInterceptorAdapter {

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        RequiresRoles requiresRoles = ((HandlerMethod) handler).getMethodAnnotation(RequiresRoles.class);
        if (requiresRoles == null)
            return true;

        UserDO user = (UserDO) request.getAttribute("user");
        Role role = user.getRole();

        Role[] roles = requiresRoles.value();
        for (Role t : roles)
            if (role == t)
                return true;
        return false;
    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
    }
}